import React from "react"
import QustionTitle from "../component/QustionTitle"
import QuestionSelect from "../component/QuestionSelect"
import { get, postFormData } from "../network/request"
import '../style/common.css'


class QuestionPage extends React.Component {
  
  constructor(props) {
    super(props)

    this.state = {
      questionList: [],
      currentIndex: 0,

      currentQuestion: {},
      currentQuestionList: [],


      answerQuestionIds: [],
      answerContents: []
    }

  }

  componentDidMount() {

    this.getQuestionList()
  }


  getQuestionList() {
    // 获取用户UserId
    let userInfo = localStorage.getItem("initUser")
    let userJson = JSON.parse(userInfo);
    var userId = userJson["user_id"];
    var workType = userJson["selectType"] || "1"; // 默认值为1

    // 根据用户的工作类型获取问题列表
    get("/jobQuestion", {"userId": userId, "jobType": workType})
      .then(response => {
        if (response && response["success"] == true && response.data) {
          let questionList = response.data.map((item, index) => {
    
            item.questionModel.questionArr = item.questionModel.questionArr.map((questionItem, index) => {
              return {
                title: questionItem,
                select: false,
                question_type: item.question_type,
                index : index
              }
            })

            item.questionModel.id = item.id
            item.questionModel.question_id = item.question_id
            item.questionModel.index = index
            item.questionModel.question_type = item.question_type
            return item.questionModel
          })

          this.setState({
            questionList: questionList,
            currentQuestion: questionList[0],
            currentIndex: 0,
            currentQuestionList : questionList[0].questionArr
          })
        }
      })
      .catch(error => {
        console.error("数据获取失败:", error);
      });
  }


  clickQuestBtn = (indexNum) => {
    // 处理选择题目逻辑
    let tempQuestion = []
    if (this.state.currentQuestion.question_type == 2) {
        this.state.currentQuestionList.forEach((item, index) => {
            if (index === indexNum) {
              item.select = !item.select
            }
            tempQuestion.push(item)
        })
    }else{
      let selectItem = this.state.currentQuestionList[indexNum]
      if (selectItem.select) {
        // 如果已经选择了，则取消选择
        selectItem.select = false
      }
      else {
        // 如果没有选择，则将其他选项取消选择
        this.state.currentQuestionList.forEach((item) => {
          item.select = false
        })
        selectItem.select = true
      }
      tempQuestion = this.state.currentQuestionList
    }

    // 更新当前题目列表和选择数量
    this.setState({
      currentQuestionList: tempQuestion
    })

  }

  clickNextBtn = () => {
    // 处理下一题逻辑
    let selectQuestionList = this.state.currentQuestionList.filter((item) => {
      return item.select === true
    })

    if (selectQuestionList.length == 0) {
      alert("Please select at least one option.")
      return
    }

    // 保存当前题目的答案
    let answerIds = []
    
    selectQuestionList.forEach((item) => {
      if (item.select) {
        answerIds.push(item.index)
      }
    })
    
    // Array To String
    let answerIdsStr = answerIds.join(',')
    let questionId = this.state.currentQuestion.question_id

    // 保存答案到状态
    this.setState((prevState) => ({
      answerQuestionIds: [...prevState.answerQuestionIds, questionId],
      answerContents: [...prevState.answerContents, answerIdsStr]
    }))


    if (this.state.currentIndex < this.state.questionList.length - 1) {
      let tempIndex = this.state.currentIndex + 1
      let tempOneDic = this.state.questionList[tempIndex]
      let questionArr = tempOneDic.questionArr

      this.setState({
        currentIndex: tempIndex,
        currentQuestion: tempOneDic,
        currentQuestionList: questionArr,
      })
      return
    }else{
      // submit Question
      let userInfo = localStorage.getItem("initUser")
      let userJson = JSON.parse(userInfo);
      var userId = userJson["user_id"];

      const formData = new FormData();
      formData.append("userId", userId);
      formData.append("questionIds", this.state.answerQuestionIds.join(';'));
      formData.append("answerContents", this.state.answerContents.join(';'));
      postFormData("/answerQuestion", formData)
        .then(response => {
          if (response && response["success"] === true) {
            // 提交成功后，清除答案状态
            this.setState({
              answerQuestionIds: [],
              answerContents: []
            });

            this.props.onClick()
          } else {
            console.error("提交失败:", response);
          }
        })
        .catch(error => {
          console.error("数据提交失败:", error);
        });
    }

    
  }

  clickSkipBtn = () => {
    // 处理跳过逻辑
    if (this.state.currentIndex < this.state.questionList.length - 1) {
      let tempIndex = this.state.currentIndex + 1
      let tempOneDic = this.state.questionList[tempIndex]
      let questionArr = tempOneDic.questionArr

      this.setState({
        currentIndex: tempIndex,
        currentQuestion: tempOneDic,
        currentQuestionList: questionArr,
      })
      return
    }

    this.props.onClick()
  }


  render() {
    return (
      <div className="QuestionPageV">

        <div className="questionTitleV">
          <p className="qustionTitle1">{'TechHub'}</p>
          <p className="qustionTitle2">{'Questions'}</p>
        </div>

        <QustionTitle title={this.state.currentQuestion.title}></QustionTitle>
        <div style={{ height: '10px' }}></div>
        {this.state.currentQuestionList.map((item, index) => {
          return (
              <QuestionSelect title={item.title} showStats={item.select === true} multStatus={item.question_type == 2} onClick={() => this.clickQuestBtn(index)}></QuestionSelect>
          )
        })}


        <div className="QustionSubmitBgV">
          <div className="QustionSkipBtn" onClick={this.clickSkipBtn}>
            <p className="skipL">{"Skip>>"}</p>
          </div>

          <div style={{ width: '10px' }}></div>
          <div className="QustionNextBtn" onClick={this.clickNextBtn}>
            <p className="nextL">{"Next Question"}</p>
          </div>
        </div>
      </div>
    )
  }
}

export default QuestionPage